#include "imGraphics.h"

using namespace imGraphics;

RendererLib::RendererLib(HINSTANCE hInstance) {
	hInst = hInstance;
	hDLL = NULL;
	pRenderer = NULL;
};

RendererLib::~RendererLib(void) {
	Release();
};

HRESULT RendererLib::MountLib(char *chAPI) {
	char buffer[300];

	hDLL = LoadLibrary(chAPI);

	if(!hDLL) {
		_snprintf_s(buffer, 300, "Unable to load graphics library '%s'", chAPI);
		MessageBox(NULL, buffer, "Imagine - Error", MB_OK | MB_ICONERROR);
		return E_FAIL;
	}

	CREATERENDERDEVICE _CreateRenderDevice = 0;
	HRESULT hr;

	// Pointer to DLL function 'CreateRenderDevice#
	_CreateRenderDevice = (CREATERENDERDEVICE) GetProcAddress(hDLL, "CreateRenderDevice");

	if( !_CreateRenderDevice ) {
		MessageBox(NULL,
			"Unable to find CreateRenderDevice function in the graphics library.",
			"Imagine - Error", MB_OK | MB_ICONERROR);
		return E_FAIL;
	}

	// Call DLL function to create the device
	hr = _CreateRenderDevice(hDLL, &pRenderer);

	if(FAILED(hr)) {
		MessageBox(NULL,
			"CreateRenderDevice() from graphics library failed.",
			"Imagine - Error",
			MB_OK | MB_ICONERROR);

		pRenderer = NULL;
		return E_FAIL;
	};

	imGraphics::g_GFX = pRenderer;

	return S_OK;
};

void RendererLib::Release(void) {
	RELEASERENDERDEVICE _ReleaseRenderDevice = 0;
	HRESULT hr;
		
	if(hDLL) {
		_ReleaseRenderDevice = (RELEASERENDERDEVICE) GetProcAddress(hDLL, "ReleaseRenderDevice");
	};

	// Call DLL's release function
	if(pRenderer) {
		hr = _ReleaseRenderDevice(&pRenderer);
		if(FAILED(hr)) {
			pRenderer = NULL;
		};
	};
}; // Release